package org.jeecg.modules.cusstyle.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.cusorder.entity.CusOrderInfo;
import org.jeecg.modules.cusorder.mapper.CusOrderInfoMapper;
import org.jeecg.modules.cusorder.service.ICusOrderInfoService;
import org.jeecg.modules.cusstyle.entity.CusStyleAccessoryInfo;
import org.jeecg.modules.cusstyle.entity.CusStyleElectroplateInfo;
import org.jeecg.modules.cusstyle.entity.CusStyleInfo;
import org.jeecg.modules.cusstyle.entity.CusStyleOtherInfo;
import org.jeecg.modules.cusstyle.entity.CusStyleStoneInfo;
import org.jeecg.modules.cusstyle.entity.CusStyleSuitInfo;
import org.jeecg.modules.cusstyle.entity.CusStyleWorkingProcedure;
import org.jeecg.modules.cusstyle.service.ICusStyleAccessoryInfoService;
import org.jeecg.modules.cusstyle.service.ICusStyleElectroplateInfoService;
import org.jeecg.modules.cusstyle.service.ICusStyleInfoService;
import org.jeecg.modules.cusstyle.service.ICusStyleOtherInfoService;
import org.jeecg.modules.cusstyle.service.ICusStyleStoneInfoService;
import org.jeecg.modules.cusstyle.service.ICusStyleSuitInfoService;
import org.jeecg.modules.cusstyle.service.ICusStyleWorkingProcedureService;
import org.jeecg.modules.cusstyle.vo.CusStyleInfoPage;
import org.jeecg.modules.manage.entity.CustomerInfo;
import org.jeecg.modules.manage.entity.GoldKarat;
import org.jeecg.modules.manage.entity.StyleAccessoryInfo;
import org.jeecg.modules.manage.entity.StyleElectroplateInfo;
import org.jeecg.modules.manage.entity.StyleInfo;
import org.jeecg.modules.manage.entity.StyleOtherInfo;
import org.jeecg.modules.manage.entity.StyleStoneInfo;
import org.jeecg.modules.manage.entity.StyleSuitInfo;
import org.jeecg.modules.manage.entity.StyleWorkingProcedure;
import org.jeecg.modules.manage.service.ICustomerInfoService;
import org.jeecg.modules.manage.service.IGoldKaratService;
import org.jeecg.modules.manage.service.IStyleAccessoryInfoService;
import org.jeecg.modules.manage.service.IStyleElectroplateInfoService;
import org.jeecg.modules.manage.service.IStyleInfoService;
import org.jeecg.modules.manage.service.IStyleOtherInfoService;
import org.jeecg.modules.manage.service.IStyleStoneInfoService;
import org.jeecg.modules.manage.service.IStyleSuitInfoService;
import org.jeecg.modules.manage.service.IStyleWorkingProcedureService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 款式资料
 * @Date:   2021-09-13
 * @Version: V1.0
 */
@Api(tags="款式资料")
@RestController
@RequestMapping("/cusStyle")
@Slf4j
public class CusStyleInfoController {
	@Autowired
	private IStyleInfoService parentStyleInfoService;
	@Autowired
	private IStyleStoneInfoService styleStoneInfoService;
	@Autowired
	private IStyleAccessoryInfoService styleAccessoryInfoService;
	@Autowired
	private IStyleWorkingProcedureService styleWorkingProcedureService;
	@Autowired
	private IStyleElectroplateInfoService styleElectroplateInfoService;
	@Autowired
	private IStyleSuitInfoService styleSuitInfoService;
	@Autowired
	private IStyleOtherInfoService styleOtherInfoService;
	
	@Autowired
	private IGoldKaratService goldKaratService;
	@Autowired
	private ICustomerInfoService customerInfoService;
	@Autowired
	private ICusStyleInfoService cusStyleInfoService;
	@Autowired
	private ICusStyleStoneInfoService cusStyleStoneInfoService;
	@Autowired
	private ICusStyleAccessoryInfoService cusStyleAccessoryInfoService;
	@Autowired
	private ICusStyleWorkingProcedureService cusStyleWorkingProcedureService;
	@Autowired
	private ICusStyleElectroplateInfoService cusStyleElectroplateInfoService;
	@Autowired
	private ICusStyleSuitInfoService cusStyleSuitInfoService;
	@Autowired
	private ICusStyleOtherInfoService cusStyleOtherInfoService;
	@Autowired
	private ICusOrderInfoService cusOrderInfoService;
	@Autowired
	private CusOrderInfoMapper cusOrderInfoMapper;
	
	/**
	 * 分页列表查询
	 *
	 * @param styleInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "款式资料-分页列表查询")
	@ApiOperation(value="款式资料-分页列表查询", notes="款式资料-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(CusStyleInfo styleInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CusStyleInfo> queryWrapper = QueryGenerator.initQueryWrapper(styleInfo, req.getParameterMap());
		Page<CusStyleInfo> page = new Page<CusStyleInfo>(pageNo, pageSize);
		IPage<CusStyleInfo> pageList = cusStyleInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param styleInfoPage
	 * @return
	 */
	@AutoLog(value = "款式资料-添加")
	@ApiOperation(value="款式资料-添加", notes="款式资料-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody CusStyleInfoPage styleInfoPage) {
		CusStyleInfo styleInfo = new CusStyleInfo();
		styleInfoPage.setCodeNum(CommonUtils.replaceBlank(styleInfoPage.getCodeNum()));//去掉特殊字符
		styleInfoPage.setName(CommonUtils.replaceBlank(styleInfoPage.getName()));//去掉特殊字符
		BeanUtils.copyProperties(styleInfoPage, styleInfo);
		cusStyleInfoService.saveMain(styleInfo, styleInfoPage.getStyleStoneInfoList(),styleInfoPage.getStyleAccessoryInfoList(),styleInfoPage.getStyleWorkingProcedureList(),styleInfoPage.getStyleElectroplateInfoList(),styleInfoPage.getStyleSuitInfoList(),styleInfoPage.getStyleOtherInfoList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *   添加
	 *
	 * @param styleInfoPage
	 * @return
	 */
	@AutoLog(value = "款式资料-添加")
	@ApiOperation(value="款式资料-添加", notes="款式资料-添加")
	@PostMapping(value = "/addByParent")
	@Transactional
	public Result<?> addByParent(@RequestBody JSONObject jsonObj) {
		String orderInfoId = jsonObj.getString("orderInfoId");
		String customerInfoId = jsonObj.getString("customerInfoId");
		String parentStyleInfoId = jsonObj.getString("parentStyleInfoId");
		JSONArray jsonGoldKaratArr = jsonObj.getJSONArray("goldKaratArr");
		JSONArray jsonGoldCountArr = jsonObj.getJSONArray("goldCountArr");
		
		String[] parentStyleInfoIds = parentStyleInfoId.split(",");
		
		boolean isSuc = false;
		if(parentStyleInfoIds != null && parentStyleInfoIds.length > 0) {
			CustomerInfo customerInfo = customerInfoService.getById(customerInfoId);
			CusOrderInfo cusOrderInfo = cusOrderInfoService.getById(orderInfoId);
			for(String mainId : parentStyleInfoIds) {
				String iGoldKaratId = "";
				Integer iGoldCount = 0;
				if(jsonGoldKaratArr != null && jsonGoldKaratArr.size() > 0) {
					for(int i = 0;i<jsonGoldKaratArr.size();i++) {
						JSONObject jo = jsonGoldKaratArr.getJSONObject(i);
						String sId = jo.getString("id");
						String goldKaratId = jo.getString("goldKaratId");
						if(sId != null && sId.equals(mainId)) {
							iGoldKaratId = goldKaratId;
						}
					}
				}
				
				if(jsonGoldCountArr != null && jsonGoldCountArr.size() > 0) {
					for(int j = 0;j<jsonGoldCountArr.size();j++) {
						JSONObject jo = jsonGoldCountArr.getJSONObject(j);
						String sId = jo.getString("id");
						Integer goldCount = jo.getInteger("count");
						if(sId != null && sId.equals(mainId)) {
							iGoldCount = goldCount;
						}
					}
				}
				
				StyleInfo parentStyleInfo = this.parentStyleInfoService.getById(mainId);
				CusStyleInfo cusStyleInfo = new CusStyleInfo();
				BeanUtils.copyProperties(parentStyleInfo, cusStyleInfo, "id");
				cusStyleInfo.setProductionRequirement(cusOrderInfo.getRemark() != null ?(cusOrderInfo.getRemark() + " "+ parentStyleInfo.getProductionRequirement()): parentStyleInfo.getProductionRequirement());//如果订单备注不为空，则复制订单备注到生产要求
				cusStyleInfo.setDeliveryDate(cusOrderInfo.getDeliveryDate());//复制交货日期
				cusStyleInfo.setOrderInfoId(orderInfoId);
				cusStyleInfo.setCustomerInfoId(customerInfoId);
				cusStyleInfo.setParentStyleInfoId(mainId);
				cusStyleInfo.setStyleCate(parentStyleInfo.getStyleCate());
				cusStyleInfo.setName(parentStyleInfo.getName());
				cusStyleInfo.setStyleImageString(parentStyleInfo.getStyleImageString());
				cusStyleInfo.setMark(customerInfo.getMark());//默认客户的字印
				cusStyleInfo.setMarkImageString(customerInfo.getMarkImageString());//默认客户的字印图片
				cusStyleInfo.setGoldKaratId(iGoldKaratId);
				cusStyleInfo.setCount(iGoldCount);
				List<StyleStoneInfo> styleStoneInfoList = styleStoneInfoService.selectByMainId(mainId);
		        List<StyleAccessoryInfo> styleAccessoryInfoList = styleAccessoryInfoService.selectByMainId(mainId);
		        List<StyleWorkingProcedure> styleWorkingProcedureList = styleWorkingProcedureService.selectByMainId(mainId);
		        List<StyleElectroplateInfo> styleElectroplateInfoList = styleElectroplateInfoService.selectByMainId(mainId);
		        List<StyleSuitInfo> styleSuitInfoList = styleSuitInfoService.selectByMainId(mainId);
		        List<StyleOtherInfo> styleOtherInfoList = styleOtherInfoService.selectByMainId(mainId);
		        
		        
		        String styleStoneInfoListJson = JSON.toJSONString(styleStoneInfoList);
		        List<CusStyleStoneInfo> cusStyleStoneInfoList = JSON.parseArray(styleStoneInfoListJson, CusStyleStoneInfo.class);
		        
		        String styleAccessoryInfoListJson = JSON.toJSONString(styleAccessoryInfoList);
		        List<CusStyleAccessoryInfo> cusStyleAccessoryInfoList = JSON.parseArray(styleAccessoryInfoListJson, CusStyleAccessoryInfo.class);
		        
		        String styleWorkingProcedureListJson = JSON.toJSONString(styleWorkingProcedureList);
		        List<CusStyleWorkingProcedure> cusStyleWorkingProcedureList = JSON.parseArray(styleWorkingProcedureListJson, CusStyleWorkingProcedure.class);
		        
		        String styleElectroplateInfoListJson = JSON.toJSONString(styleElectroplateInfoList);
		        List<CusStyleElectroplateInfo> cusStyleElectroplateInfoList = JSON.parseArray(styleElectroplateInfoListJson, CusStyleElectroplateInfo.class);
		        
		        String styleSuitInfoListJson = JSON.toJSONString(styleSuitInfoList);
		        List<CusStyleSuitInfo> cusStyleSuitInfoList = JSON.parseArray(styleSuitInfoListJson, CusStyleSuitInfo.class);
		        
		        String styleOtherInfoListJson = JSON.toJSONString(styleOtherInfoList);
		        List<CusStyleOtherInfo> cusStyleOtherInfoList = JSON.parseArray(styleOtherInfoListJson, CusStyleOtherInfo.class);
		        
		        isSuc = cusStyleInfoService.saveMain(cusStyleInfo, cusStyleStoneInfoList, cusStyleAccessoryInfoList, cusStyleWorkingProcedureList,
		        		cusStyleElectroplateInfoList, cusStyleSuitInfoList, cusStyleOtherInfoList);
		        
			}
		}

		isSuc = this.cusOrderInfoService.updateOrderInfo(orderInfoId);//更新订单信息
		return isSuc ? Result.ok("选款成功！") : Result.error("选款失败！");
	}
	
	/**
	 *   通过Excel导入
	 *
	 * @param styleInfoPage
	 * @return
	 * @throws IOException 
	 */
	@AutoLog(value = "款式资料-导入")
	@ApiOperation(value="款式资料-导入", notes="款式资料-导入")
	@PostMapping(value = "/importStyleInfo")
	@Transactional
	public Result<?> importStyleInfo(HttpServletRequest request) throws IOException {
		String orderInfoId = request.getParameter("orderInfoId");
		String customerInfoId = request.getParameter("customerInfoId");
		if(orderInfoId == null || customerInfoId == null || "".equals(orderInfoId) || "".equals(customerInfoId)) {
			return Result.error("未找到对应数据");
		}
		Result<?> importResult = this.importByExcel(request);
		if(!importResult.isSuccess()) {
			return importResult;
		}
		List<CusStyleInfo> resultList = (List<CusStyleInfo>)importResult.getResult();
		boolean isSuc = false;
		if(resultList != null && resultList.size() > 0) {
			CustomerInfo customerInfo = customerInfoService.getById(customerInfoId);
			CusOrderInfo cusOrderInfo = cusOrderInfoService.getById(orderInfoId);
			for(CusStyleInfo result : resultList) {
				result.setCodeNum(CommonUtils.replaceBlank(result.getCodeNum()));//去掉特殊字符
				result.setName(CommonUtils.replaceBlank(result.getName()));//去掉特殊字符
				if(result.getParentStyleInfoId() != null) {
					StyleInfo parentStyleInfo = this.parentStyleInfoService.getById(result.getParentStyleInfoId());
					CusStyleInfo cusStyleInfo = new CusStyleInfo();
					BeanUtils.copyProperties(parentStyleInfo, cusStyleInfo,"id");
					cusStyleInfo.setProductionRequirement(cusOrderInfo.getRemark());//复制订单备注到生产要求
					cusStyleInfo.setDeliveryDate(cusOrderInfo.getDeliveryDate());//复制交货日期
					cusStyleInfo.setOrderInfoId(orderInfoId);
					cusStyleInfo.setCustomerInfoId(customerInfoId);
					cusStyleInfo.setParentStyleInfoId(result.getParentStyleInfoId());
					cusStyleInfo.setStyleCate(parentStyleInfo.getStyleCate());
					cusStyleInfo.setName(parentStyleInfo.getName());
					cusStyleInfo.setStyleImageString(parentStyleInfo.getStyleImageString());
					cusStyleInfo.setMark(customerInfo.getMark());//默认客户的字印
					cusStyleInfo.setMarkImageString(customerInfo.getMarkImageString());//默认客户的字印图片
					cusStyleInfo.setCount(result.getCount());//数量
					cusStyleInfo.setGoldKaratId(result.getGoldKaratId());//成色
					List<StyleStoneInfo> styleStoneInfoList = styleStoneInfoService.selectByMainId(result.getParentStyleInfoId());
			        List<StyleAccessoryInfo> styleAccessoryInfoList = styleAccessoryInfoService.selectByMainId(result.getParentStyleInfoId());
			        List<StyleWorkingProcedure> styleWorkingProcedureList = styleWorkingProcedureService.selectByMainId(result.getParentStyleInfoId());
			        List<StyleElectroplateInfo> styleElectroplateInfoList = styleElectroplateInfoService.selectByMainId(result.getParentStyleInfoId());
			        List<StyleSuitInfo> styleSuitInfoList = styleSuitInfoService.selectByMainId(result.getParentStyleInfoId());
			        List<StyleOtherInfo> styleOtherInfoList = styleOtherInfoService.selectByMainId(result.getParentStyleInfoId());
			        
			        
			        String styleStoneInfoListJson = JSON.toJSONString(styleStoneInfoList);
			        List<CusStyleStoneInfo> cusStyleStoneInfoList = JSON.parseArray(styleStoneInfoListJson, CusStyleStoneInfo.class);
			        
			        String styleAccessoryInfoListJson = JSON.toJSONString(styleAccessoryInfoList);
			        List<CusStyleAccessoryInfo> cusStyleAccessoryInfoList = JSON.parseArray(styleAccessoryInfoListJson, CusStyleAccessoryInfo.class);
			        
			        String styleWorkingProcedureListJson = JSON.toJSONString(styleWorkingProcedureList);
			        List<CusStyleWorkingProcedure> cusStyleWorkingProcedureList = JSON.parseArray(styleWorkingProcedureListJson, CusStyleWorkingProcedure.class);
			        
			        String styleElectroplateInfoListJson = JSON.toJSONString(styleElectroplateInfoList);
			        List<CusStyleElectroplateInfo> cusStyleElectroplateInfoList = JSON.parseArray(styleElectroplateInfoListJson, CusStyleElectroplateInfo.class);
			        
			        String styleSuitInfoListJson = JSON.toJSONString(styleSuitInfoList);
			        List<CusStyleSuitInfo> cusStyleSuitInfoList = JSON.parseArray(styleSuitInfoListJson, CusStyleSuitInfo.class);
			        
			        String styleOtherInfoListJson = JSON.toJSONString(styleOtherInfoList);
			        List<CusStyleOtherInfo> cusStyleOtherInfoList = JSON.parseArray(styleOtherInfoListJson, CusStyleOtherInfo.class);
			        
			        isSuc = cusStyleInfoService.saveMain(cusStyleInfo, cusStyleStoneInfoList, cusStyleAccessoryInfoList, cusStyleWorkingProcedureList,
			        		cusStyleElectroplateInfoList, cusStyleSuitInfoList, cusStyleOtherInfoList);
			        if(!isSuc) {
			        	return Result.error("导入失败！");
			        }
				}
			}
		} else {
			return Result.error("表格数据0条，导入失败！");
		}
		if(isSuc) {
			isSuc = this.cusOrderInfoService.updateOrderInfo(orderInfoId);
		}
		return isSuc ? Result.ok("成功导入"+resultList.size()+"条数据！") : Result.error("导入失败！");
	}
	
	
	  /**
     * 按模板导入订单款式数据
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
	@RequestMapping(value = "/importByExcel", method = RequestMethod.POST)
	@Transactional
	public Result<?> importByExcel(HttpServletRequest request) throws IOException {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		List<CusStyleInfo> resultList = new ArrayList<>();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(0);
			params.setHeadRows(1);
			params.setSheetNum(1);
			params.setNeedSave(false);
			try {
				List<CusStyleInfo> list = ExcelImportUtil.importExcel(file.getInputStream(), CusStyleInfo.class, params);
				if(null!=list && !list.isEmpty()) {
					for (int i = 0; i < list.size(); i++) {
						CusStyleInfo vo = list.get(i); 
						String codeNum = vo.getCodeNum();//款号
						codeNum = CommonUtils.replaceBlank(codeNum);//去掉特殊字符
						vo.setCodeNum(codeNum);
						vo.setName(CommonUtils.replaceBlank(vo.getName()));//去掉特殊字符
						String goldKaratId = vo.getGoldKaratId();
						if(codeNum == null || "".equals(codeNum)) {
							return Result.error("第"+(i+1)+"行：款号不能为空！");
						} else {
							if(goldKaratId != null && !"".equals(goldKaratId)) {
								GoldKarat goldKarat = this.goldKaratService.getById(goldKaratId);
								if(goldKarat == null) {
									return Result.error("第"+(i+1)+"行：系统中找不到成色为“"+goldKaratId+"”的相关数据，请确认输入是否正确！");
								}
							}
						}
						StyleInfo styleInfo = new StyleInfo();
						Map<String,String[]> map = new HashMap<>();
						QueryWrapper<StyleInfo> queryWrapper = QueryGenerator.initQueryWrapper(styleInfo, map);
						queryWrapper.eq("code_num", vo.getCodeNum());
						StyleInfo parentStyleInfo =  this.parentStyleInfoService.getOne(queryWrapper);
						if(parentStyleInfo == null) {
							return Result.error("第"+(i+1)+"行：系统中找不到款号为“"+codeNum+"”的款式资料，请确认输入是否正确！");
						}
						vo.setParentStyleInfoId(parentStyleInfo.getId());
						resultList.add(vo);
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
		return Result.ok(resultList);
	}
	
	/**
	 *  编辑
	 *
	 * @param styleInfoPage
	 * @return
	 */
	@AutoLog(value = "款式资料-编辑")
	@ApiOperation(value="款式资料-编辑", notes="款式资料-编辑")
	@PutMapping(value = "/edit")
	@Transactional
	public Result<?> edit(@RequestBody CusStyleInfoPage styleInfoPage) {
		CusStyleInfo styleInfo = new CusStyleInfo();
		styleInfoPage.setCodeNum(CommonUtils.replaceBlank(styleInfoPage.getCodeNum()));//去掉特殊字符
		styleInfoPage.setName(CommonUtils.replaceBlank(styleInfoPage.getName()));//去掉特殊字符
		BeanUtils.copyProperties(styleInfoPage, styleInfo);
		CusStyleInfo styleInfoEntity = cusStyleInfoService.getById(styleInfo.getId());
		if(styleInfoEntity == null) {
			return Result.error("未找到对应数据");
		}
		if(styleInfoPage.getCount() == null || styleInfoPage.getCount() <= 0) {
			return Result.error("下单数量必须大于0！");
		}
		/**更新客户款式信息，包括子表*/
		cusStyleInfoService.updateMain(styleInfo, styleInfoPage.getStyleStoneInfoList(),styleInfoPage.getStyleAccessoryInfoList(),styleInfoPage.getStyleWorkingProcedureList(),styleInfoPage.getStyleElectroplateInfoList(),styleInfoPage.getStyleSuitInfoList(),styleInfoPage.getStyleOtherInfoList());
		boolean isSuc = this.cusOrderInfoService.updateOrderInfo(styleInfo.getOrderInfoId());//更新订单信息
		return isSuc ? Result.OK("编辑成功!") : Result.error("编辑失败!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "款式资料-通过id删除")
	@ApiOperation(value="款式资料-通过id删除", notes="款式资料-通过id删除")
	@DeleteMapping(value = "/delete")
	@Transactional
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		CusStyleInfo cusStyleInfo = this.cusStyleInfoService.getById(id);
		if(cusStyleInfo == null) {
			return Result.error("未找到对应数据");
		}
		cusStyleInfoService.delMain(id);//删除订单款式
		this.cusOrderInfoService.updateOrderInfo(cusStyleInfo.getOrderInfoId());//更新订单信息
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除（弃用）
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "款式资料-批量删除")
	@ApiOperation(value="款式资料-批量删除", notes="款式资料-批量删除")
	@DeleteMapping(value = "/deleteBatchBak")
	@Transactional
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cusStyleInfoService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询基础款式资料
	 *
	 * @param id（存在多个id时，以逗号,分开）
	 * @return
	 */
	@AutoLog(value = "基础款式资料-通过id查询")
	@ApiOperation(value="基础款式资料-通过id查询", notes="基础款式资料-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		List<StyleInfo> styleInfoList = new ArrayList<>();
		List<String> ids = Arrays.asList(id, ","); 
		if(!ids.isEmpty()) {
			for(String strId : ids) {
				StyleInfo styleInfo = parentStyleInfoService.getById(strId);
				styleInfoList.add(styleInfo);
			}
		}
		if(styleInfoList.size() == 0) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(styleInfoList);
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "配石资料通过主表ID查询")
	@ApiOperation(value="配石资料主表ID查询", notes="配石资料-通主表ID查询")
	@GetMapping(value = "/queryStyleStoneInfoByMainId")
	public Result<?> queryStyleStoneInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CusStyleStoneInfo> styleStoneInfoList = cusStyleStoneInfoService.selectByMainId(id);
		return Result.OK(styleStoneInfoList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "配件资料通过主表ID查询")
	@ApiOperation(value="配件资料主表ID查询", notes="配件资料-通主表ID查询")
	@GetMapping(value = "/queryStyleAccessoryInfoByMainId")
	public Result<?> queryStyleAccessoryInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CusStyleAccessoryInfo> styleAccessoryInfoList = cusStyleAccessoryInfoService.selectByMainId(id);
		return Result.OK(styleAccessoryInfoList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "工序资料通过主表ID查询")
	@ApiOperation(value="工序资料主表ID查询", notes="工序资料-通主表ID查询")
	@GetMapping(value = "/queryStyleWorkingProcedureByMainId")
	public Result<?> queryStyleWorkingProcedureListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CusStyleWorkingProcedure> styleWorkingProcedureList = cusStyleWorkingProcedureService.selectByMainId(id);
		return Result.OK(styleWorkingProcedureList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电镀资料通过主表ID查询")
	@ApiOperation(value="电镀资料主表ID查询", notes="电镀资料-通主表ID查询")
	@GetMapping(value = "/queryStyleElectroplateInfoByMainId")
	public Result<?> queryStyleElectroplateInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CusStyleElectroplateInfo> styleElectroplateInfoList = cusStyleElectroplateInfoService.selectByMainId(id);
		return Result.OK(styleElectroplateInfoList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "套件资料通过主表ID查询")
	@ApiOperation(value="套件资料主表ID查询", notes="套件资料-通主表ID查询")
	@GetMapping(value = "/queryStyleSuitInfoByMainId")
	public Result<?> queryStyleSuitInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CusStyleSuitInfo> styleSuitInfoList = cusStyleSuitInfoService.selectByMainId(id);
		return Result.OK(styleSuitInfoList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "其他资料通过主表ID查询")
	@ApiOperation(value="其他资料主表ID查询", notes="其他资料-通主表ID查询")
	@GetMapping(value = "/queryStyleOtherInfoByMainId")
	public Result<?> queryStyleOtherInfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CusStyleOtherInfo> styleOtherInfoList = cusStyleOtherInfoService.selectByMainId(id);
		return Result.OK(styleOtherInfoList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param styleInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CusStyleInfo styleInfo) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<CusStyleInfo> queryWrapper = QueryGenerator.initQueryWrapper(styleInfo, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<CusStyleInfo> queryList = cusStyleInfoService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<CusStyleInfo> styleInfoList = new ArrayList<CusStyleInfo>();
      if(oConvertUtils.isEmpty(selections)) {
          styleInfoList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          styleInfoList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<CusStyleInfoPage> pageList = new ArrayList<CusStyleInfoPage>();
      for (CusStyleInfo main : styleInfoList) {
    	  CusStyleInfoPage vo = new CusStyleInfoPage();
          BeanUtils.copyProperties(main, vo);
          List<CusStyleStoneInfo> styleStoneInfoList = cusStyleStoneInfoService.selectByMainId(main.getId());
          vo.setStyleStoneInfoList(styleStoneInfoList);
          List<CusStyleAccessoryInfo> styleAccessoryInfoList = cusStyleAccessoryInfoService.selectByMainId(main.getId());
          vo.setStyleAccessoryInfoList(styleAccessoryInfoList);
          List<CusStyleWorkingProcedure> styleWorkingProcedureList = cusStyleWorkingProcedureService.selectByMainId(main.getId());
          vo.setStyleWorkingProcedureList(styleWorkingProcedureList);
          List<CusStyleElectroplateInfo> styleElectroplateInfoList = cusStyleElectroplateInfoService.selectByMainId(main.getId());
          vo.setStyleElectroplateInfoList(styleElectroplateInfoList);
          List<CusStyleSuitInfo> styleSuitInfoList = cusStyleSuitInfoService.selectByMainId(main.getId());
          vo.setStyleSuitInfoList(styleSuitInfoList);
          List<CusStyleOtherInfo> styleOtherInfoList = cusStyleOtherInfoService.selectByMainId(main.getId());
          vo.setStyleOtherInfoList(styleOtherInfoList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "款式资料列表");
      mv.addObject(NormalExcelConstants.CLASS, CusStyleInfoPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("款式资料数据", "导出人:"+sysUser.getRealname(), "款式资料"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CusStyleInfoPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CusStyleInfoPage.class, params);
              for (CusStyleInfoPage page : list) {
            	  CusStyleInfo po = new CusStyleInfo();
                  BeanUtils.copyProperties(page, po);
                  cusStyleInfoService.saveMain(po, page.getStyleStoneInfoList(),page.getStyleAccessoryInfoList(),page.getStyleWorkingProcedureList(),page.getStyleElectroplateInfoList(),page.getStyleSuitInfoList(),page.getStyleOtherInfoList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

    
    /**
	 *   转生产单
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "款式资料-转生产单")
	@ApiOperation(value="款式资料-转生产单", notes="款式资料-转生产单")
	@GetMapping(value = "/convertProdOrder")
	public Result<?> convertProdOrder(@RequestParam(name="id",required=true) String id) {
		boolean isSuc = cusStyleInfoService.convertProdOrder(id);
		if(isSuc) {
			CusStyleInfo cusStyleInfo = cusStyleInfoService.getById(id);
			String orderInfoId = cusStyleInfo.getOrderInfoId();
			CusOrderInfo cusOrderInfo = cusOrderInfoService.getById(orderInfoId);
			if(cusOrderInfo.getStatus() == 2) {//订单仍是待转生产单状态。0暂存草稿 1待审单 -1审单不通过 2待转生产单 3待开工单 4已开工单 5完成工单
				int allOrderStyleCount = cusOrderInfoMapper.countAllOrderStyle(orderInfoId);
				int convertedStyleCount = cusOrderInfoMapper.countConvertedOrderStyle(orderInfoId);
				if(convertedStyleCount == allOrderStyleCount) {//如果该订单下的款式都已转生产单，则更新订单状态为：3待开工单
					cusOrderInfoService.updateStatus(orderInfoId, 3);
				}
			}
		}
		return isSuc ? Result.OK("转生产单成功!") : Result.error("转生产单失败!",isSuc) ;
	}
}
